<?php

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
		// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
		),
		// page action renders "static" pages stored under 'protected/views/site/pages'
		// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
		),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		$model=new Service;

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['Service']))
		{
			$model->attributes=$_POST['Service'];
			$model->status=Service::STATUS_NEW;
			if($model->save()){
				$message="Your service request is submitted. We will proceed it as soon as possible
				
				<br>The reference No. for your request is: #<strong>".$model->id.'</strong>.';
				Yii::app()->user->setFlash('service_message',$message);
				$this->redirect(array('index'));
			}
		}

		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
			echo $error['message'];
			else
			$this->render('error', $error);
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
			$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	public function actionAjaxSearchProductModel(){
		$data=Product::model()->findAll('type=:type',
		array(':type'=>$_POST['product_category']));
		
		foreach($data as $item)
		{
			echo CHtml::tag('option',
			array('value'=>$item->id),
				CHtml::encode($item->name."(".$item->model.")"),true);
		}
	}

	public function actionAjaxSearchStore(){
		if(Yii::app()->request->isAjaxRequest && isset($_GET['term']))
		{
			/* q is the default GET variable name that is used by
			 / the autocomplete widget to pass in user input
			 */
			$name = $_GET['term'];
			// this was set with the "max" attribute of the CAutoComplete widget
			$limit = isset($_GET['limit'])?min($_GET['limit'], 50):50;
			$criteria = new CDbCriteria;
			$criteria->condition = "code LIKE :sterm OR name like :sterm";
			$criteria->params = array(":sterm"=>"%$name%");
			$criteria->limit = $limit;
			$storeArray = Store::model()->findAll($criteria);
			$returnVal = array();
			foreach($storeArray as $store)
			{
				$returnVal[] = array('label'=> $store->getAttribute('name').
					'('.$store->getAttribute('code').')',
					'id'=>$store->getAttribute('id'),
					'address'=>$store->getAttribute('address'),
					'city'=>$store->getAttribute('city'),
					'state'=>$store->getAttribute('state'),
					'postcode'=>$store->getAttribute('postcode'),
					'contactName'=>$store->getAttribute('contactName'),
					'contactPhone'=>$store->getAttribute('contactPhone'),
					'contactEmail'=>$store->getAttribute('contactEmail')
				);
			}
			//          header("Cache-Control: no-cache, must-revalidate");
			//          header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
			echo CJSON::encode($returnVal);
		}
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='service-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}	
	
}